package com.yjps.house.service;

import com.yjps.common.dao.AddressDao;
import com.yjps.common.model.Address;
import com.yjps.common.util.TimeUtil;
import com.yjps.house.dao.HouseDao;
import com.yjps.house.entity.AgentForQuery;
import com.yjps.house.model.House;
import com.yjps.system.dao.AgentDao;
import com.yjps.system.dao.RoleDao;
import com.yjps.system.dao.UserDao;
import com.yjps.system.model.Agent;
import com.yjps.system.model.Role;
import com.yjps.system.model.User;
import com.yjps.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(value = "agentService")
public class AgentService {

    @Autowired
    AgentDao agentDao;

    @Autowired
    AddressDao addressDao;

    @Autowired
    UserDao userDao;

    @Autowired
    HouseDao houseDao;

    @Autowired
    RoleDao roleDao;

    @Autowired
    UserService userService;

    /**
     * 根据区域查询经纪人
     * "address": {
     * "province": "",
     * "city": "",
     * "county": "",
     * "town": ""
     * }
     * @param addressMap
     * @return
     */
    @Transactional
    public List<Agent> query( Map<String, Object> addressMap){
        String hql="from Address a where a.isValid = 1";
        Map<String,Object> params = new HashMap<>();
        for (String key : addressMap.keySet()) {
            String value = (String) addressMap.get(key);
            if (!"".equals(value)) {
                hql = hql + " and a." + key + " =:"+key/* + addressMap.get(key)*/;
                params.put(key,value);
            }
        }
        System.out.print("hql语句:" + hql);
        List<Address> addressList=addressDao.find(hql,params);
        List<Agent> agentList=new ArrayList<>();
        for (Address address :addressList){
            String hql2="from Agent a where a.shopId in (select s.id from Shop s where s.userId " +
                    "in (select b.agentsId from Building b where b.addressId =:addressId))";
            Map<String,Object>map=new HashMap<>();
            map.put("addressId", address.getId());
            agentList.addAll(agentDao.find(hql2, map));
        }
        return agentList;
    }

    /**
     * 封装经纪人查询的信息
     * @return
     */
    @Transactional
    public List<AgentForQuery> agentForQueryList(List<Agent> agentList){
        List<AgentForQuery> agentForQueries=new ArrayList<>();
        if (agentList!=null&&!agentList.isEmpty()){
            for (Agent agent :agentList){
                //查询经纪人的基本信息
                User user=queryByAgent(agent.getUserId());
                AgentForQuery agentForQuery=new AgentForQuery(user);

                //查询经纪人的出租房
                String hql2="from House h where h.sellType=0 and state=1 and isValid=1 and id in " +
                        "(select ph.houseId from PublishHistory ph where ph.agentsId =:agentsId)";
                Map<String,Object> map1=new HashMap<>();
                map1.put("agentsId",agent.getId());
                List<House> rentHouseList=houseDao.find(hql2,map1);
                if (rentHouseList!=null){
                    agentForQuery.setRentHouseList(rentHouseList);
                }

                //查询经纪人的二手房
                String hql3="from House h where h.sellType=1 and state=1 and isValid=1 and id in " +
                        "(select ph.houseId from PublishHistory ph where ph.agentsId =:agentsId)";
                Map<String,Object> map2=new HashMap<>();
                map2.put("agentsId", agent.getId());
                List<House> sellHouseList=houseDao.find(hql3,map2);
                if (sellHouseList!=null){
                    agentForQuery.setSellHouseList(sellHouseList);
                }
                agentForQuery.setAgent(agent);
                agentForQueries.add(agentForQuery);
            }
        }
        return agentForQueries;
    }

    /**
     * 查询房源对应的经纪人
     * @param houseId
     * @return
     */
    @Transactional
    public Agent queryByHouseId(int houseId){
        String hql="from Agent a where a.id in " +
                "(select agentsId from PublishHistory ph where ph.houseId =:houseId)";
        Map<String,Object> map=new HashMap<>();
        map.put("houseId",houseId);
        Agent agent=agentDao.findUniqueResult(hql,map);
        return agent;
    }

    /**
     * 查询经纪人基本信息
     * @param userId
     * @return
     */
    @Transactional
    public User queryByAgent(int userId){
        //查询经纪人的基本信息
        String hql="from User u where id =:userId";
        Map<String,Object> map=new HashMap<>();
        map.put("userId",userId);
        User user=userDao.findUniqueResult(hql, map);
        return user;
    }

    /**
     * 获取返回列表的页数
     * @param agentForQueryList
     * @param pageSize
     * @return
     */
    public int getPages(List<AgentForQuery> agentForQueryList,int pageSize){
        int size=agentForQueryList.size();
        return (size/pageSize)+1;
    }

    /**
     * 列表分页
     * @param agentForQueries
     * @param startRow
     * @param pageSize
     * @return
     */
    public List<AgentForQuery> subList(List<AgentForQuery> agentForQueries,int startRow,int pageSize){
        if (agentForQueries.size()<pageSize){
            return agentForQueries;
        }
        if ((agentForQueries.size())<=(pageSize+startRow)){
            return agentForQueries.subList(startRow,agentForQueries.size());
        }

        return agentForQueries.subList(startRow,startRow+pageSize);
    }

    /**
     * 获取门店下的所有经纪人
     * @param shopId
     * @param startRow
     * @param pageSie
     * @return
     */
    @Transactional
    public List<Agent> ListbyShop(int shopId,int startRow,int pageSie){
        String hql="from Agent a where a.shopId =:shopId and a.isValid=1";
        Map<String,Object> map=new HashMap<>();
        map.put("shopId",shopId);
        List<Agent> agents=new ArrayList<>();
        try{
            agents=agentDao.find(hql, map, startRow, pageSie);
        }catch (Exception e){
            e.printStackTrace();
        }
        return agents;
    }

    /**
     * 关联经纪人
     * @param phone
     * @param shopId
     */
    @Transactional
    public void relateAgent(String phone,int shopId){
        Role role=getAgentRole();

        String hql2="from User u where u.mobile =:phone";
        Map<String,Object> map2=new HashMap<>();
        map2.put("phone",phone);
        User user=userDao.findUniqueResult(hql2,map2);
        //增加用户一个经纪人的角色
        Set<Role> roles=user.getRoles();
        roles.add(role);
        user.setRoles(roles);
        userService.updateUser(user);

        //保存一个经纪人的必要信息
        Agent agent=new Agent();
        agent.setUserId(user.getId());
        agent.setAgentName(user.getRealName());
        agent.setShopId(shopId);
        agent.setIsValid(1);
        agent.setState(1);
        //积分初始为0
        agent.setScore("0");
        //初始化入职时间
        agent.setJoinTime(TimeUtil.getCurrentTimeInString(TimeUtil.DEFAULT_DATE_FORMAT));
        agentDao.save(agent);
    }

    /**
     * 删除经纪人
     * @param agentId
     */
    public boolean deleteAgent(int agentId){
        Role role=getAgentRole();

        //查询到对应的User
        String hql2="from User u where u.id in (select a.userId from Agent a where a.id=:agentId)";
        Map<String,Object> map2=new HashMap<>();
        map2.put("agentId", agentId);
        User user=userDao.findUniqueResult(hql2,map2);

        //删除用户经纪人的角色
        Set<Role> roles=user.getRoles();
        roles.remove(role);
        user.setRoles(roles);
        userService.updateUser(user);

        //无效化经纪人
        String hql3="update Agent a set a.isValid =:isValid where a.id = :id";
        Map<String,Object> params = new HashMap<>();
        params.put("isValid", 0);
        params.put("id", agentId);
        int affectRows=agentDao.excute(hql3,params);
        if (affectRows==0){
            return false;
        }
        return true;
    }

    /**
     * 更新经纪人信息
     * @param agent
     * @return
     */
    public boolean updateAgent(User user,Agent agent){
        userService.updateUser(user);

        String hql="update Agent a set a.sex = :sex , a.icon = :icon," +
                "a.description= :description " +
                "where a.userId = :userId";
        Map<String,Object> params = new HashMap<>();
        params.put("sex",agent.getSex());
        params.put("icon",agent.getIcon());
        params.put("description",agent.getDescription());
        params.put("userId",agent.getUserId());
        int affectRows=agentDao.excute(hql,params);
        if (affectRows==0){
            return false;
        }
        return true;
    }

    /**
     * 用户查询经纪人信息
     * @param userId
     * @return
     */
    @Transactional
    public Agent queryByUserId(int userId){
        String hql="from Agent a where a.userId =:userId";
        Map<String,Object> map=new HashMap<>();
        map.put("userId",userId);
        Agent agent=agentDao.findUniqueResult(hql, map);
        return agent;
    }

    public Role getAgentRole(){
        String hql="from Role r where r.rolename =:roleName";
        Map<String,Object> map=new HashMap<>();
        map.put("roleName", "Agent");
        Role role=roleDao.findUniqueResult(hql,map);
        return role;
    }
}
